using System;
using System.Web.Mvc;
using ilgolosone.Shared.Data;
using ilgolosone.Shared.IoC;

namespace ilgolosone.UI.Extensibility.ActionFilters
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class ConsumeUnitOfWorkAttribute : ActionFilterAttribute
    {
        private readonly IUnitOfWork _unitOfWork;

        public ConsumeUnitOfWorkAttribute() 
            : this(DependencyResolver.Resolve<IUnitOfWork>())
        { }

        public ConsumeUnitOfWorkAttribute(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _unitOfWork.Start();
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                if (filterContext.Exception == null && filterContext.Controller.ViewData.ModelState.IsValid)
                {
                    _unitOfWork.Commit();
                }
            }
            catch (Exception)
            {
                _unitOfWork.Rollback();
                throw;
            }
            finally
            {
                _unitOfWork.Dispose();
            }
        }
    }
}